const config = require("../config");
const {
  getUsersByUserAndPwd,
  addUser,
  getUsersByUser,
} = require("../db/userDB");
const JWT = require("jsonwebtoken");

exports.login = async (ctx) => {
  ctx.verifyParams({
    //必选：required 删掉也是默认为true
    username: {
      type: "string",
    },
    password: {
      type: "string",
    },
  });
  const { username, password } = ctx.request.body;
  const s = await getUsersByUserAndPwd({ username, password });
  if (s.length) {
    const userData = { ...s[0] };
    ctx.body = {
      code: 200,
      message: "登陆成功",
      data: {
        userInfo: userData,
        accessToken: JWT.sign(userData, config.secretKey),
      },
    };
  } else {
    ctx.body = {
      code: 400,
      message: "账户密码错误, 请重新登陆",
    };
  }
};

exports.register = async (ctx) => {
  ctx.verifyParams({
    //必选：required 删掉也是默认为true
    username: {
      type: "string",
    },
    password: {
      type: "string",
    },
    nickname: {
      type: "string",
    },
    avatar: {
      type: "string",
    },
  });
  const user = await getUsersByUser(ctx.request.body);
  console.log('user', user);

  if (user.length) {
    ctx.body = {
      code: 400,
      message: "该账号已经注册， 请重新注册",
    };
    return;
  }
  const s = await addUser(ctx.request.body);
  if (s.affectedRows) {
    ctx.body = {
      code: 200,
      message: "注册成功， 请登录",
    };
  } else {
    ctx.body = {
      code: 400,
      message: "注册失败, 请重新注册",
    };
  }
};
